import os
import random
import re
import string
import unicodedata

from PIL import Image


def slugify(text):
	value = []
	for character in unicode(text):
		cat = unicodedata.category(character)[0]
		if cat in 'LN':
			value.append(character)
		if cat == 'Z':
			value.append(' ')
	slug = ''.join(value).strip()
	slug = re.sub('[-\s]+', '-', slug)
	
	return slug.lower()


def write_file(file, path):
	new_path = os.path.join(path, file['filename'])
	
	try:
		new_file = open(new_path, 'w+')
		new_file.write(file['body'])
	except IOError:
		return False
	
	return new_path


def delete_uploaded_file(base_path, upload):
	path = os.path.join(base_path, upload.path)
	preview_path = os.path.join(base_path, upload.preview_path)
	
	try:
		os.remove(path)
		os.remove(preview_path)
		return True
	except:
		return False


def create_preview(path, size=100):
	image = Image.open(path)
	x = image.size[0]
	y = image.size[1]
	
	if x > y:
		new_x = x * size / y
		new_y = size
		space = (new_x - size) / 2
		box = (space, 0, space + size, size)
	else:
		new_x = size
		new_y = y * size / x
		space = (new_y - size) / 2
		box = (0, space, size, space + size)
	
	size = (new_x, new_y)
	image = image.convert('RGB')
	image = image.resize(size, Image.ANTIALIAS)
	image = image.crop(box)
	
	f, ext = os.path.splitext(os.path.basename(path))
	save_path = os.path.join(os.path.dirname(path), 'preview_%s.jpg' % f)
	
	try:
		image.save(save_path, 'JPEG', quality=100)
	except IOError:
		return False
	
	return save_path


def random_string(length=6):
	chars = string.ascii_uppercase + string.ascii_lowercase
	return ''.join(random.choice(chars) for x in range(length))